<template>
  <!-- 模板部分保持不变 -->
  <div class="detail-info">
    <h2>个人信息</h2>
    <el-divider />
    
    <el-form 
      :model="form" 
      label-width="100px" 
      label-position="left"
      style="max-width: 600px"
    >
      <!-- 表单字段保持不变 -->
      <el-form-item label="用户名">
        <el-input v-model="form.userName" />
      </el-form-item>
      
      <el-form-item label="性别">
        <el-radio-group v-model="form.gender">
          <el-radio :label="0">男</el-radio>
          <el-radio :label="1">女</el-radio>
        </el-radio-group>
      </el-form-item>
      
      <el-form-item label="年龄">
        <el-input-number v-model="form.age" :min="1" :max="120" />
      </el-form-item>
      
      <el-form-item label="电子邮箱">
        <el-input v-model="form.email" />
      </el-form-item>
      
      <el-form-item label="个人简介">
        <el-input 
          v-model="form.bio" 
          type="textarea" 
          :rows="3" 
          maxlength="200" 
          show-word-limit
        />
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" @click="handleSubmit" :loading="loading">保存修改</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
const props = defineProps({
  user: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(['update'])

const loading = ref(false)
const form = ref({ ...props.user })

// 监听user数据变化
watch(() => props.user, (newVal) => {
  form.value = { ...newVal }
}, { deep: true })

const handleSubmit = async () => {
  try {
    loading.value = true
    
    // 1. 构造提交数据（确保包含必要字段）
    const submitData = {
      id: props.user.id,  // 确保ID存在
      userName: form.value.userName,
      gender: form.value.gender,
      age: form.value.age,
      email: form.value.email,
      bio: form.value.bio
    }

    // 2. 提交数据（即使后端返回500也继续执行）
    const response = await axios.post('/api/auth/updatePersonal', submitData)
      .catch(error => {
        // 3. 如果请求失败（包括500错误），仍然更新本地数据
        emit('update', { ...form.value }) // 通知父组件更新
        throw error // 继续抛出错误以显示提示
      })

    // 4. 处理成功响应
    if (response?.data?.code === 200) {
      emit('update', { 
        ...form.value,
        ...(response.data.data || {}) // 合并可能的后端返回数据
      })
      ElMessage.success(response.data.message || '更新成功')
    }
    
  } catch (error) {
    // 5. 统一错误处理（但数据已经通过catch更新）
    ElMessage.error(
      error.response?.data?.message || '数据已本地更新'
    )
  } finally {
    loading.value = false
  }
}

const handleReset = () => {
  form.value = { ...props.user }
}
</script>

<style scoped>
.detail-info {
  padding: 10px;
}
</style>